package io.qifan.desktop.client.store.token;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.qifan.desktop.api.auth.Token;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;

@Service
@RequiredArgsConstructor
@Slf4j
public class TokenStore {

    private ObjectNode jsonNode;
    private final ObjectMapper objectMapper;

    @PostConstruct
    public void init() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        File file = new File("db.json");
        if (!file.exists()) {
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write("{\"token\": {}}");
            fileWriter.close();
        }
        jsonNode = (ObjectNode) objectMapper.readTree(file);

    }

    @PreDestroy
    public void save() {
        File file = new File("db.json");
        try {
            objectMapper.writeValue(file, jsonNode);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public Token getToken() {
        JsonNode tokenNode = jsonNode.get("token");
        try {
            return tokenNode.isEmpty() ? null : objectMapper.treeToValue(tokenNode, Token.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    public void setToken(Token token) {
        log.info("存储token：{}", token);
        jsonNode.putPOJO("token", token);
        save();
    }
}
